<?php

class Treenode {

    private $_key;
    private $_title;
    private $_level = 0;
    private $_data;
    private $_parentNode;
    private $_childNodes = array();

    public function __construct($key = 0, $title = '', $data = array()) {
        $this->_key = $key;
        $this->_title = $title;
        $this->_data = $data;
    }

    public function getKey() {
        return $this->_key;
    }

    public function setKey($key) {
        $this->_key = $key;
    }

    public function getTitle() {
        return $this->_title;
    }

    public function setTitle($title) {
        $this->_title = $title;
    }

    public function getLevel() {
        return $this->_level;
    }

    public function setLevel($level) {
        return $this->_level = $level;
    }

    public function setData($key, $value = '') {
        if (is_array($key)) {
            if (is_array($this->_data)) {
                $this->_data = array_merge($this->_data, $key);
            } else {
                $this->_data = $key;
            }
        } else {
            $key = strval($key);
            if (is_array($this->_data)) {
                $this->_data[$key] = $value;
            } else {
                $this->_data = array($key => $value);
            }
        }
    }

    public function getData($key = '') {
        if ($key && is_array($this->_data)) {
            return isset($this->_data[$key]) ? $this->_data[$key] : null;
        }
        return $this->_data;
    }

    public function getParentNode() {
        return $this->_parentNode;
    }

    public function setParentNode(&$node) {
        $this->_parentNode = $node;
    }

    /**
     * 添加子节点
     * @param Treenode $node
     * @return bool;
     */
    public function addChildNode($node) {
        $node->setParentNode($this);
        $node->setLevel($this->_level + 1);
        $this->_childNodes[] = $node;
        return true;
    }

    /**
     * 获取子节点列表
     * @return array
     */
    public function getChildNodes() {
        return $this->_childNodes;
    }

    public function hasChild() {
        if (count($this->_childNodes) > 0) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 通过key递归查找节点
     * @param object $key
     * @param bool $recursive 是否递归查找
     * @return Treenode
     */
    public function getNodeByKey($key, $recursive = true) {
        foreach ($this->_childNodes as $nd) {
            if ($nd->getKey() == $key) {
                return $nd;
            }
            if ($recursive) {
                if (count($nd->getChildNodes()) > 0) {
                    $nd1 = $nd->getNodeByKey($key, $recursive);
                    if ($nd1 != null) {
                        return $nd1;
                    }
                }
            }
        }
        return null;
    }

}
